<template>
  <span>
    <M2mTree
      :readonly="readonly"
      :records="value_display"
      :node="node"
      :parent-info="formInfo"
      @row-click="onRowClick"
      @row-new="onRowCreate"
    />

    <M2mForm
      v-model:open="modalOpen"
      :readonly="readonly"
      :record="currentRow"
      :node="node"
      :parent-info="formInfo"
      @row-remove="onRowRemove"
    />

    <M2mNew
      v-model:open="newModalOpen"
      :records="treeOptionRecords"
      :node="node"
      :parent-info="formInfo"
      @row-select="onRowSelect"
    />
  </span>
</template>

<script setup>
import M2mTree from '@/odoojs-antdv/OSubView/M2mTree.vue'
import M2mForm from '@/odoojs-antdv/OSubView/M2mForm.vue'
import M2mNew from '@/odoojs-antdv/OSubView/M2mNew.vue'

import api from '@/odoojs/index.js'

import { useWidget } from './userWidget'

import { computed, ref } from 'vue'

const props = defineProps(['modelValue', 'node', 'formInfo'])
const emit = defineEmits(['update:modelValue', 'change'])

const useData = useWidget(props, { emit })

const { readonly } = useData
const { onChange } = useData

const value_display = computed(() => {
  // console.log(fieldInfo, props.node, props.formInfo)
  const fname = props.node.name
  const { record = {} } = props.formInfo || {}
  const val = record[fname]
  return val
})

const modalOpen = ref(false)
const newModalOpen = ref(false)
const currentRow = ref({})

function onRowClick(record) {
  // console.log(record)
  currentRow.value = { ...record }
  modalOpen.value = true
}

async function onRowRemove() {
  // console.log('onRowRemove ')
  const row = currentRow.value
  const value2 = value_display.value.filter(item => item.id !== row.id)
  onChange(value2)
}

async function onRowSelect(rows) {
  // console.log('onRowSelect ', rows)

  const oldv = value_display.value
  const value2 = [...oldv, ...rows]

  onChange(value2)
}

const Relation = computed(() => {
  if (!props.node) {
    return undefined
  }
  return api.relation_node(props.node)
})

const treeview = computed(() => {
  if (!Relation.value) {
    return undefined
  }
  return Relation.value.tree
})

const treeOptionRecords = ref([])

async function getTreeOptions() {
  if (!treeview.value) {
    return []
  }
  const view = treeview.value
  const ids = value_display.value.map(item => item.id)
  const domain = ['!', ['id', 'in', ids]]
  const records = await view.search_read(domain)
  return records
}

async function onRowCreate() {
  // console.log('onRowCreate ')
  treeOptionRecords.value = await getTreeOptions()
  newModalOpen.value = true
}
</script>

<style type="text/css"></style>
